<script lang="ts">
import type { PDFDocumentProxy, PDFPageProxy } from 'pdfjs-dist'
export interface PreviewPDFProps {
}
export type PDFUrl = string | ArrayBuffer;

export interface PreviewPDFInstace {
  // 打开pdf文档
  open(url: PDFUrl): Promise<void>
  // 跳页
  jump(pageNo: number): Promise<void>
  // 获取当前页
  getCurrentPage(): PDFPageProxy | null
  // 获取当前文档
  getCurrentDocument(): PDFDocumentProxy | null
  // 获取当前页码
  getCurrentPageNo(): number
  // 获取总页数
  getPageCount(): number
}

export function usePDF() {

}

</script>

<script lang='ts' setup>
import { getDocument, GlobalWorkerOptions } from 'pdfjs-dist'
// 设置pdf worker路径
GlobalWorkerOptions.workerSrc = '/pdf.worker.mjs'
// 获取pdf预览canvas
const pdfPreviewCanvasRef = useTemplateRef<HTMLCanvasElement>('pdfPreviewCanvasRef')
// 当前页码
const currentPageNo = defineModel<number>('currentPageNo', {
  default: 1
});
// 总页数
const pageCount = defineModel<number>('pageCount', {
  default: 1
});
// pdf文件
let pdf:PDFDocumentProxy | null = null
// 当前页
let page:PDFPageProxy | null =  null


const emit = defineEmits<{
  loaded: [pdf: PDFDocumentProxy]
  pageChanged: [pageNo: number, page: PDFPageProxy]
}>()

// 加载pdf文件
async function loadPDFDocument(url: PDFUrl) {
  const loadingTask = getDocument(url);
  pdf = await loadingTask.promise;
  pageCount.value = pdf.numPages;
  emit('loaded', pdf)
}

// 渲染pdf页面
async function renderPDFPage(pageNo: number) {
  if (!pdf) {
    console.warn("PDF文档加载失败！！！")
    return
  }
  if (!pdfPreviewCanvasRef.value) {
    console.warn("Canvas加载失败！！！")
    return
  }
  if (pageNo < 1 || pageNo > pageCount.value) {
    console.warn("超出PDF文档页码范围！！！")
    return
  }
  console.log("开始渲染PDF页面：", pageNo);
  const _page = await pdf.getPage(pageNo);
  currentPageNo.value = pageNo;
  const viewport = _page.getViewport({ scale: 1 });
  pdfPreviewCanvasRef.value.width = viewport.width;
  pdfPreviewCanvasRef.value.height = viewport.height;
  var context =  pdfPreviewCanvasRef.value.getContext("2d")!;
  var renderContext = {
    canvasContext: context,
    viewport: viewport
  };
  await _page.render(renderContext).promise
  page = _page;
  console.log("成功渲染PDF页面：", pageNo)
  emit('pageChanged', pageNo, page)
}

async function open(url: PDFUrl) {
  // 加载pdf文档
  await loadPDFDocument(url)
  // 获取pdf文档第一页
  await renderPDFPage(1)
}

async function jump(pageNo: number) {
  // 加载pdf文档
  await renderPDFPage(pageNo)
}

function getCurrentPage() {
  return page;
}

function getCurrentDocument() {
  return pdf;
}

defineExpose<PreviewPDFInstace>({
  open,
  jump,
  getCurrentPage,
  getCurrentDocument,
  getCurrentPageNo() {
    return currentPageNo.value
  },
  getPageCount() {
    return pageCount.value
  },
})

</script>


<template >
  <div>
    <canvas ref="pdfPreviewCanvasRef"></canvas>
  </div>
</template>

<style scoped lang='scss'>
</style>
